<template>
  <section class="todoapp">
    <TodoHeader @todoAdd="todoAdd"></TodoHeader>
    <TodoBody
      :list="showlist"
      @changeFn="changeFn"
      @delList="delList"
      @changeAll="changeAll"
    ></TodoBody>
    <TodoFooter
      :sum="sum"
      :clearBtn="clearBtn"
      :type="type"
      @delAll="delAll"
      @typeAdd="typeAdd"
    ></TodoFooter>
  </section>
</template>

<script>
import TodoHeader from './components/TodoHeader.vue'
import TodoFooter from './components/TodoFooter.vue'
import TodoBody from './components/TodoBody.vue'
export default {
  components: {
    TodoHeader,
    TodoFooter,
    TodoBody,
  },
  data() {
    return {
      list: JSON.parse(localStorage.getItem('list')) || [
        {
          id: 1,
          flag: false,
          value: '斗破苍穹',
        },
        {
          id: 2,
          flag: true,
          value: '斗罗大陆',
        },
        {
          id: 3,
          flag: false,
          value: '遮天',
        },
        {
          id: 4,
          flag: false,
          value: '完美世界',
        },
      ],
      type: 'all',
    }
  },
  methods: {
    // 添加
    todoAdd(name) {
      // console.log(name)
      this.list = [
        ...this.list,
        {
          id: +new Date(),
          flag: false,
          value: name,
        },
      ]
    },

    changeFn(id, flag) {
      // console.log(id, flag)
      this.list.forEach((item) => {
        if (item.id === id) {
          item.flag = flag
        }
      })
    },
    delList(id) {
      const event = this.list.find((item) => item.id === id)
      if (!event.flag) return alert('o.O????')
      this.list = this.list.filter((item) => item.id !== id)
    },
    delAll() {
      return (this.list = this.list.filter((item) => !item.flag))
    },
    typeAdd(value) {
      this.type = value
    },
    changeAll(flag) {
      // console.log(1)
      this.list.forEach((item) => (item.flag = flag))
    },
  },
  computed: {
    sum() {
      return this.list.filter((item) => !item.flag).length
    },
    clearBtn() {
      return this.list.some((item) => item.flag)
    },
    showlist() {
      switch (this.type) {
        case 'all':
          return this.list
        case 'active':
          return this.list.filter((item) => !item.flag)
        case 'completed':
          return this.list.filter((item) => item.flag)
        default:
          return this.list
      }
    },
  },
  watch: {
    list: {
      deep: true,
      handler(newVal) {
        localStorage.setItem('list', JSON.stringify(newVal))
      },
    },
  },
}
</script>

<style></style>
